package com.hl.manage.controller;


import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hl.manage.entity.Department;
import com.hl.manage.entity.Group;
import com.hl.manage.entity.User;
import com.hl.manage.service.IDepartmentService;
import com.hl.manage.service.IGroupService;
import com.hl.manage.service.IUserService;
import com.hl.manage.utils.SendResult;

/**
 * <p>
 * 用户信息表 前端控制器
 * </p>
 *
 * @author Helei
 * @since 2021-03-10
 */
@RestController
@RequestMapping("/user")
public class UserController {
	@Autowired
	IUserService userService;
	@Autowired
	IGroupService groupService;
	@Autowired
	IDepartmentService idepartmentService;
	@Autowired
	private IUserService user;
	
	/**
	 * 根据获取用户
	 * @param id
	 * @return
	 */
	@RequestMapping("/getuser")
	public User getUser(@RequestParam(name = "id") String id){
		return userService.getById(id);
	}
	/**
	 * 修改或者增加用户
	 * @param param
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping("updatebyid")
	public String updateById(@Param("param") String param) throws UnsupportedEncodingException {
		SendResult sResult = new SendResult();
		JSONObject jsonObject = JSONObject.parseObject(URLDecoder.decode(param.replaceAll("%25", ""), "UTF-8"));
		Group group =  groupService.getById(Integer.parseInt(jsonObject.get("gName").toString()));
		if(!group.getCompanyId().toString().equals(jsonObject.get("cName").toString())) {
			sResult.setCode(400001);
			sResult.setMsg("操作失败，所选角色组和公司不一致");
			sResult.setData(null);
			return sResult.toString();
		}
		User user = new User();
		if (jsonObject.get("id").toString().isEmpty()) {
			user.setId(null);
		}else {
			user.setId(Integer.parseInt(jsonObject.get("id").toString()));
		}
		
		if (!jsonObject.get("password").toString().isEmpty()) {
			user.setPassword(DigestUtils.md5DigestAsHex(jsonObject.get("password").toString().getBytes()));
		}
		user.setAccount(jsonObject.get("account").toString());
		user.setCompanyId(Integer.parseInt(jsonObject.get("cName").toString()));
		user.setDepartmentId(Integer.parseInt(jsonObject.get("dName").toString()));
		user.setGroupId(Integer.parseInt(jsonObject.get("gName").toString()));
		user.setName(jsonObject.get("name").toString());
		if(userService.saveOrUpdate(user)) {
			sResult.setCode(200);
			sResult.setMsg("操作成功");
			sResult.setData(null);
			return sResult.toString();
		}else {
			sResult.setCode(400001);
			sResult.setMsg("添加失败，请重试");
			sResult.setData(null);
			return sResult.toString();
		}
		
	}
	/**
	 * 根据公司id获取公司下面的所有部门
	 * @param companyId
	 * @return json {resultmsg: {code: 200, msg: "操作成功", data: []}}
	 */
	@RequestMapping("getdepartment")
	public String  getDepartment(@RequestParam(name = "companyId")Integer companyId) {
		SendResult sResult = new SendResult();
		QueryWrapper<Department> qde = Wrappers.query();
		qde.eq("type",1).eq("parent_id", companyId);
		List<Department>  listdee  = idepartmentService.list(qde);
		sResult.setCode(200);
		sResult.setMsg("操作成功");
		sResult.setData(listdee.toString());
		return sResult.toString();
	}
	
	/**
	 * 分页查询
	 * @param page
	 * @param limit
	 * @param request
	 * @return JSON
	 */
	@RequestMapping("/page")
	public String getAllUser(@RequestParam(name = "page")Integer page,@RequestParam(name = "limit") Integer limit,HttpServletRequest request) {
		//获取登录用户的信息
		HttpSession session = request.getSession();
		QueryWrapper<User> qWrapper = Wrappers.query();
		qWrapper.eq("account",session.getAttribute("account"));
		User userres = user.getOne(qWrapper);
		Integer comIdInteger =  userres.getCompanyId();
		System.out.println("公司id="+comIdInteger);
		if (comIdInteger.equals(1)) {
			IPage<User> iPage = new Page<User>(page, limit);
			List<User> list =  userService.page(iPage, null).getRecords();
			List<Object> list2 = new ArrayList<Object>();
			for (User user : list) {
				JSONObject jObject = JSONArray.parseObject(user.toString());
				
				//获取所有公司
				QueryWrapper<Department> qWrapp = Wrappers.query();
				qWrapp.eq("type",0);
				List<Department>  listde  = idepartmentService.list(qWrapp);
				
				//获取所有部门
				QueryWrapper<Department> qde = Wrappers.query();
				qde.eq("type",1).eq("parent_id", userres.getCompanyId());
				
				List<Department>  listdee  = idepartmentService.list(qde);
				
				//获取所有角色组
				List<Group>  gList  = groupService.list();
				
				jObject.put("cList", listde);
				jObject.put("dList", listdee);
				jObject.put("gList", gList);
				jObject.put("dName", idepartmentService.getById(user.getDepartmentId()).getName());
				jObject.put("cName", idepartmentService.getById(user.getCompanyId()).getName());
				jObject.put("gName", groupService.getById(user.getGroupId()).getName());
				jObject.put("total", iPage.getTotal());
				jObject.put("loginId", userres.getId());
				jObject.put("logingId", userres.getGroupId());
				jObject.put("loginCId", userres.getCompanyId());
				list2.add(jObject);
			}
			SendResult sResult = new SendResult();
			sResult.setCode(200);
			sResult.setMsg("查询成功");
			sResult.setData(list2.toString());
			return sResult.toString();
		}else {
			List<User> list =  userService.pageBycompany(comIdInteger);
			List<Object> list2 = new ArrayList<Object>();
			for (User user : list) {
				JSONObject jObject = JSONArray.parseObject(user.toString());
				
				//获取所有公司
				
				List<Department>  listde  = idepartmentService.findByPIT(0, userres.getCompanyId(), userres.getCompanyId());

				//获取所有部门
				QueryWrapper<Department> qde = Wrappers.query();
				qde.eq("type",1).eq("parent_id", comIdInteger);
				List<Department>  listdee  = idepartmentService.list(qde);
				
				//获取所有角色组
				QueryWrapper<Group> gWrapper = Wrappers.query();
				gWrapper.eq("id", userres.getGroupId());
				List<Group>  gList2  = groupService.list(gWrapper);
				
				jObject.put("cList", listde);
				jObject.put("dList", listdee);
				jObject.put("gList", gList2);
				
				jObject.put("dName", idepartmentService.getById(user.getDepartmentId()).getName());
				jObject.put("cName", idepartmentService.getById(user.getCompanyId()).getName());
				jObject.put("gName", groupService.getById(user.getGroupId()).getName());
				jObject.put("total", userService.count());
				jObject.put("loginId", userres.getId());
				jObject.put("logingId", userres.getGroupId());
				jObject.put("loginCId", userres.getCompanyId());
				list2.add(jObject);
			}
			SendResult sResult = new SendResult();
			sResult.setCode(200);
			sResult.setMsg("查询成功");
			sResult.setData(list2.toString());
			return sResult.toString();
		}
	}
	/**
	 * 根据id删除
	 * @param id
	 * @param request
	 * @return
	 */
	@RequestMapping("/deletebyid")
	public String delById(@RequestParam(name = "id") String id,HttpServletRequest request){
		HttpSession session = request.getSession();
		if(session.getAttribute("loginId").toString().equals(id)) {
			SendResult sResult = new SendResult();
			sResult.setCode(400001);
			sResult.setMsg("删除用户和当前登录用户一致不允许删除！");
			sResult.setData(null);
			return sResult.toString();
		}else if(id.equals("1")){
			SendResult sResult = new SendResult();
			sResult.setCode(400001);
			sResult.setMsg("系统默认超级管理员不允许删除！");
			sResult.setData(null);
			return sResult.toString();
		}
		if(userService.removeById(id)) {
			SendResult sResult = new SendResult();
			sResult.setCode(200);
			sResult.setMsg("删除成功");
			sResult.setData(null);
			return sResult.toString();
		}else {
			SendResult sResult = new SendResult();
			sResult.setCode(400001);
			sResult.setMsg("删除失败，请重试！");
			sResult.setData(null);
			return sResult.toString();
		}
	}
	/**
	 * 用户登录
	 * @param account
	 * @param pass
	 * @param request
	 * @return
	 */
	@RequestMapping("/login")
	public String login(@RequestParam(name = "account") String account,@RequestParam(name = "pass") String pass,HttpServletRequest request){
		String passString = DigestUtils.md5DigestAsHex(pass.getBytes());
		List<User> user = userService.findAllUser(account,passString);
		if(user.isEmpty()) {
			SendResult sResult = new SendResult();
			sResult.setCode(400001);
			sResult.setMsg("账号或者密码错误");
			sResult.setData(null);
			return sResult.toString();
		}else {
			QueryWrapper<User> wrappers = Wrappers.query();
			wrappers.eq("account", account);
			User userone = userService.getOne(wrappers);
					
			HttpSession session = request.getSession();
			session.setAttribute("account", account);
			session.setAttribute("loginCompany", userone.getCompanyId());
			session.setAttribute("loginDepartmemt", userone.getDepartmentId());
			session.setAttribute("loginGroup", userone.getGroupId());
			session.setAttribute("loginId", userone.getId());
			
			session.setMaxInactiveInterval(1800);
			SendResult sResult = new SendResult();
			sResult.setCode(200);
			sResult.setMsg("登陆成功");
			
			JSONObject jsonObject = new JSONObject();
			jsonObject.put("name", userone.getName());
			jsonObject.put("group", groupService.getById(userone.getGroupId()).getName());
			jsonObject.put("company", idepartmentService.getById(userone.getCompanyId()).getName());
			
			
			Date date = new Date();
			userone.setPassword(null);
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("token", passString);
			map.put("timestamp", date.getTime());
			map.put("loginmsg",jsonObject);
			JSONObject jsonObj=new JSONObject(map);
			sResult.setData(jsonObj.toJSONString());
			return sResult.toString();
		}
	}
	/**
	 * 退出登录
	 * @param request
	 * @return
	 */
	@RequestMapping("/loginout")
	public String loginout(HttpServletRequest request) {
		request.getSession().removeAttribute("account");
		SendResult sResult = new SendResult();
		sResult.setCode(200);
		sResult.setMsg("退出登录成功");
		sResult.setData(null);
		return sResult.toString();
	}
}
